﻿using RRQMCore.ByteManager;
using RRQMSocket;
using System;
using System.Collections;
using System.Text;
using System.Text.Json;
using System.Text.Unicode;

namespace TCPJson
{
    class Program
    {
        static void Main(string[] args)
        {
            LanTcpService service = new LanTcpService();
            service.IsCheckClientAlive = true;
            service.Bind(5600, 5);
            service.ClientConnected += ClientConnected;
            service.ClientDisconnected += ClientDisconnected;
            Console.WriteLine("成功绑定");
            Console.ReadKey();
        }

        private static void ClientDisconnected(object sender, MesEventArgs e)
        {
            LanTcpSocketClient client = (LanTcpSocketClient)sender;
            Console.WriteLine($"{client.Name}已断开");
        }

        private static void ClientConnected(object sender, MesEventArgs e)
        {
            LanTcpSocketClient client = (LanTcpSocketClient)sender;
            Console.WriteLine($"{client.Name}已连接");
        }
    }

    class LanTcpService : TcpService<LanTcpSocketClient>
    {
        protected override void OnCreatSocketCliect(LanTcpSocketClient tcpSocketClient, CreatOption creatOption)
        {
            if (creatOption.NewCreat)
            {
                tcpSocketClient.DataHandlingAdapter = new JsonDataHandlingAdapter();
            }
            base.OnCreatSocketCliect(tcpSocketClient, creatOption);
        }
    }

    class LanTcpSocketClient : TcpSocketClient
    {
        //public LanTcpSocketClient(BytePool bytePool):base (bytePool) { }
        protected override void HandleReceivedData(ByteBlock byteBlock, object obj)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            string msg = Encoding.UTF8.GetString(byteBlock.Buffer, 0, (int)byteBlock.Position);
            //var options = new JsonSerializerOptions();
            //options.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(UnicodeRanges.All);

            //TestClass test = JsonSerializer.Deserialize<TestClass>(msg);

            //var json = JsonSerializer.Serialize(test, options);
            Console.WriteLine($"接收的长度是{byteBlock.Length}，位置是{byteBlock.Position},信息是:{msg}");
        }
    }

    public class TestClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class JsonDataHandlingAdapter : DataHandlingAdapter
    {
        private ByteBlock Temp;
        protected override void PreviewReceived(ByteBlock byteBlock)
        {
            //Console.WriteLine("----------------接收的新数据-------------------");
            byte[] buffer = byteBlock.Buffer;
            int length = (int)byteBlock.Length;
            if (Temp != null)
            {
                Temp.Write(byteBlock.Buffer, 0, length);
                buffer = Temp.Buffer;
                length = (int)Temp.Length;
            }

            string msg = Encoding.UTF8.GetString(buffer, 0, length);
            if (msg.Contains("}{"))
            {
                //Console.WriteLine("----------------发生粘包-------------------");
                string[] mes = msg.Split("}{");
                for (int i = 0; i < mes.Length; i++)
                {
                    string str = mes[i];
                    if (i == 0)
                    {
                        str += "}";
                    }
                    else if (i == mes.Length - 1)
                    {
                        str = "{" + str;
                        int start = StringCount(str, "{");
                        int end = StringCount(str, "}");
                        if (start == end)
                        {

                            if (Temp != null)
                            {
                                Temp = null;
                            }
                        }
                        else
                        {
                            byte[] surPlus = Encoding.UTF8.GetBytes(str);

                            if (Temp != null)
                            {
                                Temp = null;
                            }
                            Temp = BytePool.GetByteBlock(surPlus.Length);

                            Temp.Write(surPlus);
                            //Console.WriteLine("----------------数据不完整-------------------");
                            break;
                        }

                    }
                    else
                    {
                        str = "{" + str + "}";
                    }
                    //Console.WriteLine(str);
                    PreviewHandle(str);
                }
            }
            else
            {
                //Console.WriteLine(msg);
                PreviewHandle(msg);
            }
        }

        protected override void PreviewSend(byte[] buffer, int offset, int length)
        {
            throw new NotImplementedException();
        }

        private int StringCount(string source, string match)
        {
            int count = 0;
            if (source.Contains(match))
            {
                string temp = source.Replace(match, "");
                count = (source.Length - temp.Length) / match.Length;
            }
            return count;
        }
        private void PreviewHandle(string msg)
        {
            byte[] handle = Encoding.UTF8.GetBytes(msg);
            int length = handle.Length;
            ByteBlock byteBlock = BytePool.GetByteBlock(length);
            byteBlock.Write(handle);
            byteBlock.Position = length;
            GoReceived(byteBlock, null);
            byteBlock.Dispose();
        }
    }
}
